import Meta from "../../components/Meta";
import GoodsList from "../../components/Goods/List";
import GoodsHeader from "../../components/Goods/Header";
import React, { useState, useRef, useEffect } from "react";
import { request } from "../../utils/request";
import { transData } from "../../utils/tool";
import Header from "../../components/Header/Header";
import Nav from "../../components/Nav/Nav";
import Footer from "../../components/Footer/Footer";
import { Modal, Button, Form, Progress, Rate, Tooltip, Divider, Row, Col, Dropdown, Menu, Space, Carousel, Image, List, Avatar, Spin, Collapse, Input, message, Checkbox, Drawer, Table, Switch, Select } from 'antd';
// import Divider from "../../components/Divider";
import { StarOutlined, HeartOutlined, UserOutlined } from '@ant-design/icons';
import router from "next/router";
import Link from "next/link";
import styles from './detail.module.scss';
import moment from 'moment';
import { DownOutlined, CheckCircleFilled } from '@ant-design/icons';
import Scrollbars from 'react-custom-scrollbars';
function Detail(props) {
  console.log('skusku', props.sku)

  const [sizeIndex, setSizeIndex] = useState(0);
  const [colorIndex, setColorIndex] = useState(0);
  const [skuData, setSku] = useState();
  const [imgIndex, setImgIndex] = useState(0);
  const [btnLoading, setBtnLoading] = useState(false);
  const [list, setList] = useState([])
  const swiperRef = useRef(null)
  const [form] = Form.useForm()
  const [rate, setRate] = useState(5)
  const [commentLoading, setCommentLoading] = useState(false);
  const [sizeData, setSize] = useState([])
  const [colorData, setColor] = useState([])
  const [showGuide, setShowGuide] = useState(false)
  const [columns, setColumns] = useState([])
  const [dataSource, setDataSource] = useState([])
  const [originDataSource, setOriginDataSource] = useState([])
  const [inchData, setInchData] = useState([]);
  const [qty,setButQty] = useState(1)
  const settings = {
    infinite: true,
    speed: 500,
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: true,
    nextArrow: <NextArrow />,
    prevArrow: <PrevArrow />,
    lazyLoad: true,
    slickGoTo: 1,
    afterChange: (e) => {
      setImgIndex(e)
    }
  };

  function NextArrow(props) {
    const { className, style, onClick } = props;
    return (
      <div
        className='slide-arrow-next'
        style={{ ...style, display: "block" }}
        onClick={onClick}
      ><img src="/image/icon-left.png" className="slide-arrow-icon" /></div>
    );
  }

  function PrevArrow(props) {
    const { className, style, onClick } = props;
    return (
      <div
        className='slide-arrow-prev'
        style={{ ...style, display: "block" }}
        onClick={onClick}
      ><img src="/image/icon-right.png" className="slide-arrow-icon" /></div>
    );
  }

  const handleClickSize = (item, index) => {
    console.log('item', item)
    if (item.sellOut) {
      return;
    }
    const sku = props.goodsData.sku.find(item => item.color == props.colorData[colorIndex].id && item.size == props.sizeData[index].id);
    const sellOutData = props.goodsData.sku
      .filter(item => item.size == props.sizeData[index].id && item.stockQty === 0)
      .map(item => item.color)
    console.log('sellOutData', sellOutData)
    const newColor = [...colorData]
    newColor.forEach(item => {
      if (sellOutData.includes(item.id.toString())) {
        item.sellOut = true
      } else {
        item.sellOut = false
      }
    })
    setSku(sku);
    setColor(newColor)
    setSizeIndex(index)
  }

  const handleClickColor = (item, index) => {
    if (item.sellOut) {
      return;
    }
    const sku = props.goodsData.sku.find(item => item.color == props.colorData[index].id && item.size == props.sizeData[sizeIndex].id);

    const sellOutData = props.goodsData.sku
      .filter(item => item.color == props.colorData[index].id && item.stockQty === 0)
      .map(item => item.size)

    const newSize = [...sizeData]
    newSize.forEach(item => {
      if (sellOutData.includes(item.id.toString())) {
        item.sellOut = true
      } else {
        item.sellOut = false
      }
    })
    console.log('sellOutData2', sizeData)
    setSize(newSize)
    setSku(sku);
    setColorIndex(index)
  }

  const handleClickImgPagi = (index) => {
    setImgIndex(index)
    console.log(swiperRef.current)
    swiperRef.current?.goTo(index);
  }

  const getCommentList = async (rate) => {
    const params = {
      goodsId: props.pid,
      current: 1,
      pageSize: 5
    }
    if (rate) {
      params.rate = rate
    }
    setCommentLoading(true)
    const ret = await request(`${props.apiUrl}/api/product/showComment`, params)
    if (ret.code === 100000) {
      setList(ret.data.rows)
      setRate(ret.data.rate)
    }
    setCommentLoading(false)
  }

  useEffect(() => {
    console.log('useeffect')
    getCommentList()
    setSku(props.sku)
    setSize(props.sizeData)
    setColor(props.colorData)
    const tableData = props.goodsData.sizeInfo ? JSON.parse(props.goodsData.sizeInfo) : [];
    console.log('tableData', tableData)
    console.log('props.sizeData', props.sizeData)
    console.log('aa', props.goodsData)
    const newTableData = tableData.length ? [...tableData.map(item => {
      return Object.assign({}, item)
    })] : []
    newTableData.length && newTableData.forEach(item => {
      for (let key in item) {
        if (!['id', 'position'].includes(key)) {
          let values = item[key].split('-');
          item[key] = parseFloat(values[0] / 2.54).toFixed(1)
          if (values[1]) {
            item[key] += `-${parseFloat(values[1] / 2.54).toFixed(1)}`
          }
        }
      }
    })
    console.log('newTableData', newTableData)
    const sizeGuideArr = props.sizeData.map(item => {
      return {
        title: item.name,
        dataIndex: item.id
      }
    })

    sizeGuideArr.unshift({
      title: '',
      dataIndex: 'position',
      width: '120'

    })
    console.log('sizeGuideArr', sizeGuideArr)

    setColumns(sizeGuideArr);
    setDataSource(tableData)
    setInchData(newTableData)
    setOriginDataSource(tableData)
  }, [props.pid])

  const [isModalVisible, setIsModalVisible] = useState(false);
  const showModal = () => {
    if (!localStorage.getItem('token')) {
      Modal.confirm({
        title: 'Please login',
        content: 'You have to login to do next step',
        onOk() {
          router.push(`/account/login?back=/detail/${props.pid}`);
        },
      })

      return;
    }
    setIsModalVisible(true);
  };
  const handleOk = async () => {
    setIsModalVisible(false);
    const orderData = [{
      goodsId: props.pid,
      selectSize: props.sizeData[sizeIndex].id,
      selectColor: props.colorData[colorIndex].id,
      selectImg: skuData?.album[imgIndex].url,
      goodsName: props.goodsData?.productName,
      goodsSubName: props.goodsData?.productSubName,
      price: skuData?.price,
      selectSizeName: props.sizeData[sizeIndex].name,
      selectColorName: props.colorData[colorIndex].enName
    }]
    const ret = await request(`${props.apiUrl}/api/cart/add`, {
      goodsId: props.pid,
      buyQty: qty,
      totalAmount: (skuData?.price*qty).toFixed(2),
      skuId: skuData?.id,
      goodsUrl: skuData?.album[imgIndex].url
    });
    if (ret.code === 100000) {

      router.push('/shop/mybag')
    } else {
      message.error('fail to add bag')
    }


  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const { Panel } = Collapse;

  function callback(key) {
    console.log(key);
  }


  const [isModalVisible1, setIsModalVisible1] = useState(false);

  const showModal1 = () => {
    if (!localStorage.getItem('token')) {
      Modal.confirm({
        title: 'Please login',
        content: 'You have to login to do next step',
        onOk() {
          router.push(`/account/login?back=/detail/${props.pid}`);
        },
      })

      return;
    }
    setIsModalVisible1(true);
  };
  const onFinish = async (values) => {
    setBtnLoading(true)
    const ret = await request(`${props.apiUrl}/api/product/addComment`, { ...values, goodsId: props.pid });
    if (ret.code === 100000) {
      Modal.confirm({
        title: 'Thanks for you feedback',
        content: 'Your feedback helps others find the perfect gear and helps to improve our products. Reviews are typically posted within 72 hours, however, due to high volume our response times have been longer than normal. Don’t sweat—your review will be shared, or you’ll hear back from us soon.',
      })
    }
    setBtnLoading(false)
    setIsModalVisible1(false);

  };

  const handleCancel1 = () => {
    setIsModalVisible1(false);
  };

  const sortRate = (e) => {

    getCommentList(e)
  }
  const changeSwitch = (e) => {
    console.log('e', e)

    if (e) {
      setDataSource(originDataSource)
    } else {
      setDataSource(inchData)
    }

  }
  const handleChange = (value) => {
    console.log(`selected ${value}`);
    setButQty(value)
  };
  const { Option } = Select;
  const provinceData = ['Zhejiang', 'Jiangsu'];
  const cityData = {
    Zhejiang: ['Hangzhou', 'Ningbo', 'Wenzhou'],
    Jiangsu: ['Nanjing', 'Suzhou', 'Zhenjiang'],
  };
  const [cities, setCities] = useState(cityData[provinceData[0]]);
  const [secondCity, setSecondCity] = useState(cityData[provinceData[0]][0]);

  const handleProvinceChange = (value) => {
    setCities(cityData[value]);
    setSecondCity(cityData[value][0]);
  };

  const onSecondCityChange = (value) => {
    setSecondCity(value);
  };
  const { TextArea } = Input;
  return (
    <div className="goods-detail">
      <Meta>
        <title>NINAMOKA-detail</title>
      </Meta>
      <Header />
      <Nav navData={props.navData} pagesData={props.pagesData} />
      <Row>
        <Col xs={0} md={3}></Col>
        <Col className="productdetail" xs={24} md={18}>
          
          <Row gutter={20}>
            {/* left start */}
            <Col xs={24} md={11}>
              <Carousel {...settings} ref={swiperRef}>
                {
                  skuData?.album.map((item, index) => {
                    if (index < 5) {
                      return (
                        <div className="thumbnails" key={item.id}>
                          <Image src={item.url} />
                        </div>
                      )
                    }
                  })
                }
              </Carousel>
              <div className="pagi-imgs">
                {
                  skuData?.album.map((item, index) => {
                    if (index < 5) {
                      return (
                        <div className={imgIndex === index ? "pagi-imgs-box active" : "pagi-imgs-box"}
                          key={item.id}
                          onClick={() => handleClickImgPagi(index)}>
                          <img
                            src={item.url}
                            title="Casual Shirt With Ruffle Hem"
                            alt={props.goodsData.productName}
                          />
                        </div>
                      )
                    }

                  })
                }
              </div>
            </Col>
            {/* <Col xs={24} md={9}>
              <Scrollbars style={{ height: '855px',width:'100%' }} className={styles.scroll}>
                <Row gutter={[10, 10]} >
                <Image.PreviewGroup>
                  {
                    props?.albums.map((item, index) => {
                      return (
                        <Col  xs={12} md={12}>
                          <Image src={item.url} key={index} className="album-item"></Image>
                        </Col>
                      )
                    })
                  }
                </Image.PreviewGroup>
                </Row>
              </Scrollbars>
            </Col> */}
            {/* left end */}
            {/* right start */}

            <Col xs={24} md={8}>
              <div className="prodetail">
                <div className="top-tabs">
                  <a className="Women">{props.goodsData?.categoryName?.pName}</a>
                  <span className="Slash">/</span>
                  <a className="Women">{props.goodsData?.categoryName?.cateName}</a>
                  <span className="Slash"></span>
                </div>
                <h1 className="productpage-title">
                  {props.goodsData?.productName}
                </h1>
                <h2 className="productpage-label">
                  {props.goodsData?.productSubName}
                </h2>
                {/* <h2 className="productpage-title productSubName">
                  {props.goodsData?.productSubName}
                </h2> */}

                <div className="productpage-price-box">
                  <div>
                    <div className="productpage-original">
                      <h2 className="productpage-price">${skuData?.price} USD</h2>
                      {/* <span className="productpage-save">Save More With GapCash! Or Extra 20% Off With Code YOURS</span> */}
                    </div>
                    {/* <h2 className="productpage-originalPrice">${skuData?.price} USD</h2> */}

                  </div>
                  
                </div>
                <hr />

                <div className="prop-box">
                  <div className="prop-box-header">
                    <span className="prop-box-header-text">Select Color:</span>
                    <span className="prop-box-header-content">{props.colorData[colorIndex].enName}</span>
                  </div>
                  <ul className="prop-box-content">
                    {
                      colorData && colorData.map((item, index) => (
                        <li
                          key={index}
                          className={colorIndex === index ? `li-color active  ${item.sellOut ? 'sell-out' : ''}` : `li-color ${item.sellOut ? 'sell-out' : ''}`}
                          onClick={() => handleClickColor(item, index)}
                          style={{ background: item.name }}
                        >
                          <span className="cricle"></span>
                        </li>
                      ))
                    }
                  </ul>
                </div>
                <div className="prop-box">
                  <div className="prop-box-header">
                    <span className="prop-box-header-text">Select Size</span>
                    <span className="prop-box-header-content">{props.sizeData[sizeIndex].name}</span>
                    <span className="prop-box-header-right" onClick={() => setShowGuide(true)}>Size Guide</span>
                  </div>
                  <ul className="prop-box-content">
                    {
                      sizeData && sizeData.map((item, index) => (
                        <li key={index} className={sizeIndex === index ? `li-size active  ${item.sellOut ? 'sell-out' : ''}` : `li-size ${item.sellOut ? 'sell-out' : ''}`} onClick={() => handleClickSize(item, index)}>{item.name}</li>
                      ))
                    }
                  </ul>
                </div>
                <hr />
                {/* <div className="prop-box">
                  <div className="prop-box-header">
                    <span className="prop-box-header-text">Shoping Now</span>
                  </div>
                </div>
                <ul className="prop-box-content shopping">
                  {
                    props.goodsData && props.goodsData.buyLinks.map((item, index) => {
                      return (<li key={index}>
                        <a href={item.url} target="_blank" className="mall-link">
                          <img src={item.logoUrl} className="mall-logo" />
                          <span>{item.name}</span>
                        </a>
                      </li>
                      )
                    })
                  }
                </ul> */}
                <div className="add-button">
                  <Select
                    defaultValue="1"
                    style={{
                      width: 100,
                    }}
                    onChange={handleChange}
                    className="ant-select-selector"
                  >
                    <Option value="1">1</Option>
                    <Option value="2">2</Option>
                    <Option value="3">3</Option>
                    <Option value="4">4</Option>
                    <Option value="5">5</Option>
                    <Option value="6">6</Option>
                    <Option value="7">7</Option>
                    <Option value="8">8</Option>
                  </Select>
                  <Button onClick={showModal} type="primary" block size="large" danger style={{ marginTop: '15px' }}>ADD TO BAG</Button>

                </div>
                
                <div className="details-box">
                  <span className="details">Details</span>
                  <div className="Designed-box">
                    {/* <a className="Designed">Designed for Running</a>
                    <a className="Lightweight">Lightweight, Stretch Ripstop Fabric</a>
                    <a className="Relaxed">Relaxed Fit, Hip Length</a>
                    <a className="Product">Product Features</a> */}
                    <Collapse onChange={callback} bordered={false} ghost expandIconPosition="right" >
                      {
                        props.goodsData?.tagsArr.map((item, index) => {
                          return (
                            <Panel header={item.tagTitle} key={index}>
                              {
                                item.tagContent && item.tagContent.split(',').map((items, i) => {
                                  return <a className="detalis-item" key={i}>{items}</a>
                                })
                              }

                            </Panel>
                          )
                        })
                      }

                    </Collapse>
                  </div>
                </div>
                {/* <div className="details-box">
                <div className="details">Details</div>
                
                </div> */}
                <div className="details-box">
                <div className="details">Display</div>
                <div dangerouslySetInnerHTML={{ __html: props.goodsData.description }} style={{ marginBottom: '70px' }}></div>
                </div>
              </div>

            </Col>
            {/* right end */}
            {/* recomoned start */}
            <Col xs={0} md={5}>
              <div className="like-box">
                <h1 className="title">
                  You May Like
                </h1>
                {
                  props.confData[0].goods.map(item => {
                    return (
                      <div className="like-box-item" key={item.id}>
                        <Link href={`/detail/${item.id}`}>
                          <img src={JSON.parse(item.productImg)[0].url} />
                        </Link>

                      </div>
                    )
                  })
                }

              </div>
            </Col>
            {/* recomoned end */}
          </Row>
        </Col>
        <Col xs={0} md={3}></Col>
      </Row>

      <Divider />
      <GoodsHeader data={{
        title: "PRODUCT DISPLAY",
        hideSubtitle: true
      }} />
      <Row>
        <Col xs={1} md={4}></Col>
        <Col xs={22} md={16}>
          <div dangerouslySetInnerHTML={{ __html: props.goodsData.description }} style={{ marginBottom: '70px' }}>

          </div>

        </Col>
        <Col xs={1} md={4}></Col>

      </Row>
      <Row>
        <Col xs={1} md={4}>

        </Col>
        <Col xs={22} md={16}>
          <Row gutter={[20, 20]}>
            {
              props?.albums.map((item, index) => {
                return (
                  <Col md={8}>
                    <img src={item.url} key={index} className="album-item"></img>
                  </Col>
                )
              })
            }
          </Row>
        </Col>
        <Col xs={1} md={4}>

        </Col>
      </Row>
      {/* <Divider /> */}
      <Spin spinning={commentLoading}>
        <Row>
          <Col xs={24} md={24}>
            <div className={styles['left-title']}>
              <Divider className={styles['left-reviews']}>Reviews</Divider>
            </div>
          </Col>
        </Row>
        <Row gutter={20}>
          <Col xs={1} md={2}>

          </Col>
          <Col xs={7} md={6}>
            {/* left */}

            <div className={styles["right-title"]}>
              <Rate className={styles["ant-rate"]} value={rate} disabled />
              <span className={styles["rate-reviews"]}>6 Reviews</span>
            </div>
            <div className={styles["reviews-box"]}>
              <Tooltip title="Show only 5 star reviews">
                <div className={styles["stars-box"]}>
                  <span className={styles["stars"]}>5 Stars</span>
                  <Progress className={styles["ant-progress-line"]} percent={2} showInfo={false} strokeColor="#000" strokeWidth="12px" strokeLinecap="butt" />
                  <span >2</span>
                </div>
              </Tooltip>
              <Tooltip title="Show only 4 star reviews">
                <div className={styles["stars-box"]}>
                  <span className={styles["stars"]}>4 Stars</span>
                  <Progress className={styles["ant-progress-line"]} percent={1} showInfo={false} strokeColor="#000" strokeWidth="12px" />
                  <span>1</span>
                </div>
              </Tooltip>
              <Tooltip title="Show only 3 star reviews">
                <div className={styles["stars-box"]}>
                  <span className={styles["stars"]}>3 Stars</span>
                  <Progress className={styles["ant-progress-line"]} percent={2} showInfo={false} strokeColor="#000" strokeWidth="12px" />
                  <span>2</span>
                </div>
              </Tooltip>
              <Tooltip title="Show only 2 star reviews">
                <div className={styles["stars-box"]}>
                  <span className={styles["stars"]}>2 Stars</span>
                  <Progress className={styles["ant-progress-line"]} percent={0} showInfo={false} strokeColor="#000" strokeWidth="12px" />
                  <span>0</span>
                </div>
              </Tooltip>
              <Tooltip title="Show only 1 star reviews">
                <div className={styles["stars-box"]}>
                  <span className={styles["stars"]}>1 Stars</span>
                  <Progress className={styles["ant-progress-line"]} percent={1} showInfo={false} strokeColor="#000" strokeWidth="12px" />
                  <span>1</span>
                </div>
              </Tooltip>

            </div>

          </Col>
          <Col xs={1} md={1}></Col>
          <Col xs={7} md={6}>
            <Button className={styles["ant-btn-primary"]} onClick={showModal1} type="primary">WRITE A REVIEW</Button>

          </Col>
          <Col xs={1} md={1}></Col>
          <Col xs={6} md={6}></Col>
          <Col xs={1} md={2}></Col>
        </Row>

        <Row>
          <Col xs={2} md={2}>
          </Col>
          <Col xs={20} md={20}>
            <span className={styles["customerReviews"]}>6 Customer Reviews</span>

          </Col>
          <Col xs={2} md={2}>
          </Col>
        </Row>

        <Divider className={styles['customerReviews-divider']} />
        <Row>
          <Col xs={2} md={2}>
          </Col>
          <Col xs={20} md={20}>
            <div className={styles["filter-box"]}>
              <span className={styles["filter"]}>Filter Reviews By</span>
              <div className={styles["drop-down"]}>
                <div className={styles["select"]}>
                  <div className={styles["selectBox"]}>
                    <Select
                      defaultValue={provinceData[0]}
                      style={{
                        width: 170,
                      }}
                      onChange={handleProvinceChange}
                    >
                      {provinceData.map((province) => (
                        <Option key={province}>{province}</Option>
                      ))}
                    </Select>
                  </div>
                  <div>
                    <Select
                      style={{
                        width: 170,
                      }}
                      value={secondCity}
                      onChange={onSecondCityChange}
                    >
                      {cities.map((city) => (
                        <Option key={city}>{city}</Option>
                      ))}
                    </Select>
                  </div>

                </div>
                <div>
                  <Select
                    defaultValue="lucy"
                    style={{
                      width: 170,
                    }}
                    onChange={handleChange}
                  >
                    <Option value="jack">Jack</Option>
                    <Option value="lucy">Lucy</Option>
                    <Option value="disabled" disabled>
                      Disabled
                    </Option>
                    <Option value="Yiminghe">yiminghe</Option>
                  </Select>
                </div>
              </div>


            </div>

          </Col>
          <Col xs={1} md={2}></Col>
        </Row>
        <Row>
          <Col xs={1} md={2}></Col>
          <Col xs={22} md={20}>
            <div className={styles["ant-rate-box"]}>
              <Rate className={styles["ant-rate"]} value={rate} disabled />
              <span className={styles["rate-reviews"]}>Super Comfy and Flowy</span>
              <span className={styles["rate-days"]}>Jen,5 days ago</span>
              <span className={styles["rate-content"]}>I am usually a size medium in Gap dresses, but I got a small as per other reviews saying it is more loose and small fits just right. Love the softness and the flow of the dress. It compliments my tan :)</span>
              <div className={styles["rate-moreBox"]}>
                <a className={styles["rate-more"]}>More Detail</a>
                <DownOutlined />
              </div>
              <div className={styles["rate-verified"]}>
                <CheckCircleFilled />
                <span className={styles["rate-verifiedSpan"]}>Verified Buyer</span>
                <CheckCircleFilled />
                <span className={styles["rate-verifiedSpan"]}>Sweepstakes Entry</span>
              </div>
              <Divider className={styles['customerReviews-divider']} />
            </div>

            <div className={styles["ant-rate-box"]}>
              <Rate className={styles["ant-rate"]} value={rate} disabled />
              <span className={styles["rate-reviews"]}>Super Comfy and Flowy</span>
              <span className={styles["rate-days"]}>Jen,5 days ago</span>
              <span className={styles["rate-content"]}>I am usually a size medium in Gap dresses, but I got a small as per other reviews saying it is more loose and small fits just right. Love the softness and the flow of the dress. It compliments my tan :)</span>
              <div className={styles["rate-moreBox"]}>
                <a className={styles["rate-more"]}>More Detail</a>
                <DownOutlined />
              </div>
              <div className={styles["rate-verified"]}>
                <CheckCircleFilled />
                <span className={styles["rate-verifiedSpan"]}>Verified Buyer</span>
                <CheckCircleFilled />
                <span className={styles["rate-verifiedSpan"]}>Sweepstakes Entry</span>
              </div>
              <Divider />
            </div>
          </Col>
          <Col xs={1} md={2}></Col>
        </Row>

      </Spin>
      <GoodsHeader data={{
        title: "RELATED PRODUCTS",
        hideSubtitle: true
      }} />
      <GoodsList data={props.confData[0].goods} />
      <GoodsHeader data={{
        title: "CUSTOMERS ALSO LIKED",
        hideSubtitle: true
      }} />
      <GoodsList data={props.confData[0].goods} />

      <Footer navData={props.navData} siteData={props.siteInfo} />
      <Modal title="Add To Bag" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>

        <div className="Model-left">
          <img className="Model-img" src={skuData?.album[imgIndex].url}></img>
          <div className="Swiftly-box">
            <h1 className="fb">{props.goodsData?.productName}</h1>
            
            <span className="Swiftly-span"><span className="fb">Size:</span>{props.sizeData[sizeIndex].name}</span>
            <span className="Swiftly-span"><span className="fb">Color:</span>{props.colorData[colorIndex].enName}</span>
            <span className="Swiftly-span"><span className="fb">Qty:</span>{qty}</span>
            <span className="Swiftly-span"><span className="fb">${skuData?.price} USD</span></span>
          </div>
        </div>
      </Modal>
      <Modal footer={null} width={900} visible={isModalVisible1} onCancel={() => setIsModalVisible1(false)}>
        <div className={styles["ant-modal-body"]}>
          <img className={styles["body-img"]} src={skuData?.album[imgIndex].url}></img>
          <div className={styles["body-right"]}>
            <span style={{ marginBottom: '20px' }}>Write a review for</span>
            <Form
              form={form}
              layout="vertical"
              onFinish={onFinish}>
              <Form.Item
                label="Your overall rating"
                name="rate"
                initialValue={5}
                rules={[
                  {
                    required: true,
                    message: "please select rate"
                  },
                ]}
              >
                <Rate className={styles["ant-rate"]} />
              </Form.Item>
              <Form.Item
                label="Review Title"
                name="title"
                rules={[
                  {
                    required: true,
                    message: "please enter review title"
                  },
                ]}
              >
                <Input size="large" placeholder="Basic usage" />
              </Form.Item>
              <Form.Item
                label="Review(25-500 characters)"
                name="content"
                rules={[
                  {
                    required: true,
                    message: "please enter review content"
                  },
                ]}
              >
                <TextArea minLength={25} maxLength={500} rows={4} />
              </Form.Item>
              <Form.Item
                label="First Name, Last Initial"
                name="name"
                rules={[
                  {
                    required: true,
                    message: "please enter first name, last initial"
                  },
                ]}
              >
                <Input size="large" placeholder="Ex:Allison S." />
              </Form.Item>
              <Form.Item
                label="Email"
                name="email"
                rules={[
                  {
                    required: true,
                    message: "please enter email"
                  },
                ]}
              >
                <Input size="large" placeholder="Email only used to verify review." />
              </Form.Item>
              <Form.Item>
                <Button className={styles["body-button"]} type="primary" htmlType="submit" loading={btnLoading} block>Submit</Button>
              </Form.Item>

            </Form>

          </div>
        </div>
      </Modal>
      <Drawer
        visible={showGuide}
        title="Size Guide"
        width={700}
        onClose={() => setShowGuide(false)}
      >
        <div className={styles.table}>
          <Table
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            scroll={{ x: 600 }}
            rowKey="id"
          />
          <div className={styles.switch}>
            <Switch checkedChildren="cm" unCheckedChildren="in" defaultChecked onChange={changeSwitch} />
          </div>
        </div>
        <h1 className={styles['title-h1']}>HOW TO MEASURE</h1>
        <h2 className={styles['title-h2']}>1. Bust </h2>
        <p className={styles['p-content']}>Measure under your arms. Around the fullest part of your chest</p>
        <h2 className={styles['title-h2']}>2. Waist </h2>
        <p className={styles['p-content']}>Measure around your natural waistline at belly button level.</p>
        <h2 className={styles['title-h2']}>3. Hips </h2>
        <p className={styles['p-content']}>Measure around the fullest part of your body at the top of your leg.</p>
        <div dangerouslySetInnerHTML={{ __html: props.goodsData.sizeExtraInfo }} className="size-guide"></div>
      </Drawer>
    </div>
  );
}

export default Detail;
export async function getServerSideProps(ctx) {
  console.log('ctx serverside===', ctx.params)
  const apiUrl = process.env.APIURL;
  console.log('apiurl', apiUrl)
  // Fetch data from external API
  const navData = await request(`${apiUrl}/api/client/nav`);
  const newNavData = transData(navData.data, "id", "pid");
  const pagesData = await request(`${apiUrl}/api/client/articles`);
  const goodsData = await request(`${apiUrl}/api/product/detail`, {
    id: ctx.params.pid
  })
  const confData = await request(`${apiUrl}/api/client/homeGoods`);
  const propertyData = await request(`${apiUrl}/api/client/queryProps`);
  const imgs = await request(`${apiUrl}/api/product/getAlbums`, { id: ctx.params.pid });
  // Pass data to the page via props


  const colorData = propertyData.data.color.filter(item => {
    return goodsData.data.color.includes(item.id.toString())
  })
  const sizeData = propertyData.data.size.filter(item => {
    return goodsData.data.size.includes(item.id.toString())
  })
  const sku = goodsData.data.sku.find(item => item.color == colorData[0].id && item.size == sizeData[0].id);
  console.log('sku', sku)
  return {
    props: {
      navData: newNavData,
      pagesData: pagesData.data,
      goodsData: goodsData.data,
      confData: confData.data,
      colorData,
      sizeData,
      sku,
      pid: ctx.params.pid,
      apiUrl,
      albums: imgs.data.album
    }
  }
}